<template>
  <div class="region-cascader">
    <el-cascader
      v-model="selectedValues"
      :options="options"
      :props="cascaderProps"
      :placeholder="placeholder"
      :disabled="disabled"
      :clearable="clearable"
      :show-all-levels="showAllLevels"
      :collapse-tags="collapseTags"
      :separator="separator"
      :size="size"
      :filterable="filterable"
      style="width: 100%"
      @change="handleChange"
      @visible-change="handleVisibleChange"
    />
  </div>
</template>

<script>
import { getProvinces, getCitiesByProvinceId, getDistrictsByCityId } from '@/api/system/region'

export default {
  name: 'RegionCascader',
  props: {
    // v-model 绑定的值
    value: {
      type: Array,
      default: () => []
    },
    // 占位符
    placeholder: {
      type: String,
      default: '请选择省/市/区'
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否可清空
    clearable: {
      type: Boolean,
      default: true
    },
    // 是否显示完整路径
    showAllLevels: {
      type: Boolean,
      default: true
    },
    // 多选时是否折叠Tag
    collapseTags: {
      type: Boolean,
      default: false
    },
    // 分隔符
    separator: {
      type: String,
      default: ' / '
    },
    // 尺寸
    size: {
      type: String,
      default: ''
    },
    // 是否可搜索
    filterable: {
      type: Boolean,
      default: false
    },
    // 级联层级（1=省份，2=城市，3=区县）
    level: {
      type: Number,
      default: 3,
      validator(value) {
        return [1, 2, 3].includes(value)
      }
    },
    // 是否在选择城市时也触发change事件
    changeOnSelect: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectedValues: [],
      options: [],
      cascaderProps: {
        value: 'regionId',
        label: 'regionName',
        children: 'children',
        lazy: true,
        lazyLoad: this.lazyLoad,
        changeOnSelect: this.changeOnSelect
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        this.selectedValues = val || []
      },
      immediate: true
    }
  },
  created() {
    this.loadProvinces()
  },
  methods: {
    // 懒加载数据
    async lazyLoad(node, resolve) {
      const { level, value } = node
      let children = []
      
      try {
        if (level === 0) {
          // 加载省份
          const response = await getProvinces()
          children = response.data || []
        } else if (level === 1 && this.level >= 2) {
          // 加载城市
          const response = await getCitiesByProvinceId(value)
          children = response.data || []
        } else if (level === 2 && this.level >= 3) {
          // 加载区县
          const response = await getDistrictsByCityId(value)
          children = response.data || []
        }
        
        // 为每个节点设置leaf属性
        children.forEach(item => {
          if (this.level === 1) {
            // 只显示省份
            item.leaf = true
          } else if (this.level === 2) {
            // 显示到城市
            item.leaf = level >= 1
          } else {
            // 显示到区县
            item.leaf = level >= 2
          }
        })
        
        resolve(children)
      } catch (error) {
        console.error('加载地区数据失败:', error)
        resolve([])
      }
    },
    
    // 初始加载省份数据
    async loadProvinces() {
      try {
        const response = await getProvinces()
        const provinces = response.data || []
        
        // 设置省份的leaf属性
        provinces.forEach(province => {
          province.leaf = this.level === 1
        })
        
        this.options = provinces
      } catch (error) {
        console.error('加载省份数据失败:', error)
      }
    },
    
    // 选项变化处理
    handleChange(value) {
      this.selectedValues = value
      this.$emit('input', value)
      this.$emit('change', value)
      
      // 获取选中的节点信息
      if (value && value.length > 0) {
        this.getSelectedNodes(value)
      }
    },
    
    // 获取选中节点的详细信息
    getSelectedNodes(values) {
      // 通过级联选择器的getCheckedNodes方法获取选中的节点
      this.$nextTick(() => {
        const cascader = this.$children[0]
        if (cascader && cascader.getCheckedNodes) {
          const nodes = cascader.getCheckedNodes()
          const nodeData = nodes.map(node => ({
            regionId: node.value,
            regionName: node.label,
            regionLevel: node.level + 1,
            pathNames: node.pathLabels,
            pathValues: node.path
          }))
          this.$emit('node-change', nodeData)
        }
      })
    },
    
    // 下拉框显示/隐藏
    handleVisibleChange(visible) {
      this.$emit('visible-change', visible)
    },
    
    // 获取当前选中的完整路径名称
    getSelectedLabels() {
      const cascader = this.$children[0]
      if (cascader && cascader.getCheckedNodes) {
        const nodes = cascader.getCheckedNodes()
        return nodes.map(node => node.pathLabels)
      }
      return []
    },
    
    // 获取当前选中的节点数据
    getSelectedNodes() {
      const cascader = this.$children[0]
      if (cascader && cascader.getCheckedNodes) {
        return cascader.getCheckedNodes()
      }
      return []
    },
    
    // 清空选择
    clearSelection() {
      this.selectedValues = []
      this.$emit('input', [])
      this.$emit('change', [])
    }
  }
}
</script>

<style lang="scss" scoped>
.region-cascader {
  width: 100%;
  
  ::v-deep .el-cascader {
    width: 100%;
  }
}
</style>